package borderPatrol.Calculators;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import borderPatrol.Data.Move;
import borderPatrol.misc.CFRInformationSet;

public class BPStrategyCalculator extends StrategyCalculator {

	File regretFile;
	BufferedWriter writer;

	public BPStrategyCalculator() {
		regretFile = new File("regret.txt");
		try {
			writer = new BufferedWriter(new FileWriter(regretFile));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void updateStrategy(int iteration) {
		updateStrategy("1", iteration, 1);
		updateStrategy("2", iteration, 2);
	}

	private void updateStrategy(String id, int iteration, int sign) {

		CFRInformationSet set = gameTree.get(id);

		float[] currentRegret = set.getRegret();
		float[] currentStrategy = set.getStrategy();

		if (set.getIsTerminal() != 0) {
			return;
		}
		
		set.computeAverageStrategy();

		float setValue = 0;
		float sum = 0;

		for (int i = 0; i < set.getValues().length; i++) {
			setValue += set.getValues()[i] * set.getStrategy()[i];
		}

		for (int i = 0; i < set.getRegret().length; i++) {
			currentRegret[i] += (set.getValues()[i] - setValue);
			sum += Math.max(currentRegret[i] / iteration, 0);
		}

		for (int i = 0; i < currentStrategy.length; i++) {
			currentStrategy[i] = (sum > 0) ? Math.max(currentRegret[i] / iteration, 0) / sum : 1 / (float) currentRegret.length;
		}

		for (Move move : set.getMoves()) {
			updateStrategy(id + "." + move, iteration, sign);
		}

//		if (id.length() == 1) {
//
//			float value = getMax(currentRegret) / iteration;
//
//			System.out.println(value);
//
//			try {
//				writer.write(Float.toString(value));
//				writer.newLine();
//				writer.flush();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//
//		}

	}

	private float getMax(float[] array) {

		System.out.println(Arrays.toString(array));

		float max = Float.NEGATIVE_INFINITY;
		int indexOfMax = -1;

		for (int i = 0; i < array.length; i++) {
			if (Float.compare(max, array[i]) < 0) {
				max = array[i];
				indexOfMax = i;
			}
		}

		return array[indexOfMax];
	}

}
